package com.rtsapp.server.utils;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

public class StringUtils {

    public static boolean isEmpty(String input) {
        return (input == null || input.trim().length() == 0);
    }

    public static String getStackTrack(Exception e) {

        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        pw.flush();
        pw.close();
        sw.flush();
        String value = sw.getBuffer().toString();
        try {
            sw.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return value;

    }


    /**
     * join string.
     *
     * @param array String array.
     * @return String.
     */
    public static String join(String[] array) {
        if (array.length == 0) return "";
        StringBuilder sb = new StringBuilder();
        for (String s : array)
            sb.append(s);
        return sb.toString();
    }


    public static String upperFirstChar(String name) {
        if (name == null || name.length() < 1) {
            return name;
        }

        return name.replaceFirst("" + name.charAt(0), "" + Character.toUpperCase(name.charAt(0)));
    }


    public static int toInt32(String input) {

        if (input.endsWith(".0")) {
            input = input.substring(0, input.length() - 2);
        }
        return Integer.parseInt(input);
    }


    public static int getCharCount(String str) {
        int charCount = 0;
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (c >= '\u4e00' && c <= '\u9fa5') {
                charCount += 3;
            } else {
                charCount++;
            }
        }
        return charCount;
    }


    /**
     * 相似度比较
     *
     * @param strA
     * @param strB
     * @return
     */

    public static double similarDegree(String strA, String strB) {

        String newStrA = removeSign(strA);

        String newStrB = removeSign(strB);

        int temp = Math.max(newStrA.length(), newStrB.length());

        int temp2 = longestCommonSubstring(newStrA, newStrB).length();

        return temp2 * 1.0 / temp;

    }


    private static String removeSign(String str) {

        StringBuffer sb = new StringBuffer();

        for (char item : str.toCharArray())

            if (charReg(item)) {

                //System.out.println("--"+item);

                sb.append(item);

            }

        return sb.toString();

    }


    private static boolean charReg(char charValue) {

        return (charValue >= 0x4E00 && charValue <= 0X9FA5)

                || (charValue >= 'a' && charValue <= 'z')

                || (charValue >= 'A' && charValue <= 'Z')

                || (charValue >= '0' && charValue <= '9');

    }


    private static String longestCommonSubstring(String strA, String strB) {

        char[] chars_strA = strA.toCharArray();

        char[] chars_strB = strB.toCharArray();

        int m = chars_strA.length;

        int n = chars_strB.length;

        int[][] matrix = new int[m + 1][n + 1];

        for (int i = 1; i <= m; i++) {

            for (int j = 1; j <= n; j++) {

                if (chars_strA[i - 1] == chars_strB[j - 1])

                    matrix[i][j] = matrix[i - 1][j - 1] + 1;

                else

                    matrix[i][j] = Math.max(matrix[i][j - 1], matrix[i - 1][j]);

            }

        }

        char[] result = new char[matrix[m][n]];

        int currentIndex = result.length - 1;

        while (matrix[m][n] != 0) {

            if (matrix[m][n] == matrix[m][n - 1])

                n--;

            else if (matrix[m][n] == matrix[m - 1][n])

                m--;

            else {

                result[currentIndex] = chars_strA[m - 1];

                currentIndex--;

                n--;

                m--;

            }
        }

        return new String(result);

    }

    /**
     * 将字符串转换为国际化格式
     * 例
     * <p>
     * i18nConversion("say ${hellow} ${world}!!!", {"${hellow}", "${world}"}, {"Hellow", "World"}, "%s", "^%&")
     * 得到的结果是"say %s %s!!!^%&Hellow^%&World"
     *
     * @param template 模板
     * @param keys     参数键
     * @param values   参数值
     * @return 结果
     */
    public static String i18nConversion(String template, String[] keys, String[] values) {
        return i18nConversion(template, keys, values, "%s", "^%&");
    }

    /**
     * 将字符串转换为国际化格式
     * 例
     * <p>
     * i18nConversion("say ${hellow} ${world}!!!", {"${hellow}", "${world}"}, {"Hellow", "World"}, "%s", "^%&")
     * 得到的结果是"say %s %s!!!^%&Hellow^%&World"
     *
     * @param template    模板
     * @param keys        参数键
     * @param values      参数值
     * @param placeholder 占位符
     * @param separator   分隔符
     * @return 结果
     */
    public static String i18nConversion(String template, String[] keys, String[] values, String placeholder, String separator) {

        //整体字符串结果
        StringBuilder toMultiLanguageString = new StringBuilder();

        //参数字符串结果
        StringBuilder argsStr = new StringBuilder();

        template = template.replace("%", "%%");

        while (true) {
            //找到的最小关键词位置
            int index = -1;
            //找到的关键词
            String key = "";
            //找到的关键词索引
            int keyIndex = -1;

            //遍历所有关键词keys
            for (int i = 0; i < keys.length; i++) {
                String tmpKey = keys[i];
                int tmpIndex = template.indexOf(tmpKey);
                //如果关键词存在 并且 ( 没有其他找到的关键词 或者 比之前找到的关键词靠前 )
                if (tmpIndex != -1 && (index == -1 || tmpIndex < index)) {
                    index = tmpIndex;
                    key = tmpKey;
                    keyIndex = i;
                }
            }
            //如果没有找到任何关键词,则说明已经处理完成,将剩余模板片段追加进来
            if (index < 0) {
                toMultiLanguageString.append(template);
                break;
            }
            //如果关键词位置大于0 说明关键词前面还有其他非关键词字符串,将他们截取出来追加进去
            if (index > 0) {
                String tmpStr = template.substring(0, index);
                toMultiLanguageString.append(tmpStr);
            }
            //追加一个占位符
            toMultiLanguageString.append(placeholder);
            //追加参数分隔符
            argsStr.append(separator);
            //追加参数
            argsStr.append(values[keyIndex]);

            template = template.substring(index + key.length());
        }

        toMultiLanguageString.append(argsStr);

        return toMultiLanguageString.toString();
    }


}
